package com.baselibrary.utils;

import android.app.Activity;
import android.text.TextUtils;

import com.baselibrary.manager.LoadingManager;

/**
 * @author 关忆北丶
 * @description:
 * @date :2020/8/25 17:08
 */
public class VideoDownloadUtil {

    public static void download(final Activity activity, final String url, final String suffix) {
        if (TextUtils.isEmpty(url)) {
            ToastUtils.showShort(activity.getApplicationContext(), "下载链接出错");
            return;
        }


        LoadingManager.showLoadingDialog(activity,"正在下载...");
        //下载视频
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final String fileName = System.currentTimeMillis() + suffix;
                    String filePath = MediaFileUtils.getAppPath(activity.getApplicationContext()) + fileName;
                    MediaFileUtils.DownLoadFile(activity, url, filePath, new MediaFileUtils.DownloadListener() {
                        @Override
                        public void onDownloadSuccess(String path) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    LoadingManager.hideLoadingDialog(activity);
                                    ToastUtils.showShort(activity.getApplicationContext(), "已下载至相册");
                                }
                            });
                        }

                        @Override
                        public void onDownloading() {

                        }

                        @Override
                        public void onDownloadFailed() {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    LoadingManager.hideLoadingDialog(activity);
                                    ToastUtils.showShort(activity.getApplicationContext(), "请打开手机存储权限");
                                }
                            });
                        }
                    });

                }
            }).start();
        } catch (Exception e) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LoadingManager.hideLoadingDialog(activity);
                    ToastUtils.showShort(activity.getApplicationContext(), "下载失败");
                }
            });
        }
    }

}
